package com.ukefu.webim.web.handler.admin.callcenter;

import com.sun.org.apache.regexp.internal.RE;
import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.webim.service.repository.ExtentionRepository;
import com.ukefu.webim.service.repository.NumberPoolExtentionRelaRepository;
import com.ukefu.webim.service.repository.NumberPoolRepository;
import com.ukefu.webim.service.repository.PbxHostRepository;
import com.ukefu.webim.util.CallCenterUtils;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.NumberPool;
import com.ukefu.webim.web.model.NumberPoolExtentionRela;
import com.ukefu.webim.web.model.SipTrunk;
import freemarker.template.TemplateException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin/callcenter/numberpool")
public class CallCenterNumberPoolController extends Handler {
	
	@Autowired
	private PbxHostRepository pbxHostRes ;
	
	@Autowired
	private NumberPoolRepository numberPoolRepository;

	@Autowired
	private ExtentionRepository extentionRepository;

	@Autowired
	private NumberPoolExtentionRelaRepository numberPoolExtentionRelaRepository;

	@RequestMapping(value = "/index")
    @Menu(type = "callcenter" , subtype = "numberpool" , access = false )
    public ModelAndView index(ModelMap map , HttpServletRequest request , @Valid final String hostid,@Valid final NumberPool numberPool) {
		if(!StringUtils.isBlank(hostid) || (numberPool != null && StringUtils.isNotBlank(numberPool.getHostid()))){

			map.addAttribute("pbxHost" , pbxHostRes.findByIdAndOrgi(StringUtils.isBlank(hostid)?numberPool.getHostid():hostid, super.getOrgi(request)));

			Page<NumberPool> numberPoolList = numberPoolRepository.findAll(new Specification<NumberPool>() {
				@Override
				public Predicate toPredicate(Root<NumberPool> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
					List<Predicate> list = new ArrayList<Predicate>();

					if(numberPool != null && StringUtils.isNotBlank(numberPool.getNumber())){
						list.add(cb.like(root.get("number").as(String.class),"%" +  numberPool.getNumber() + "%" ));
					}

					list.add(cb.equal(root.get("hostid").as(String.class),StringUtils.isBlank(hostid)?numberPool.getHostid():hostid));

					Predicate[] p = new Predicate[list.size()];
					query.where(cb.and(list.toArray(p)));
					query.orderBy(cb.desc(root.get("createtime")));

					return query.getRestriction();
				}
			},new PageRequest(super.getP(request), super.getPs(request))) ;

			map.addAttribute("numberPoolList" , numberPoolList);
			map.addAttribute("numberPool" , numberPool);
		}
		return request(super.createRequestPageTempletResponse("/admin/callcenter/numberpool/index"));
    }
	
	@RequestMapping(value = "/add")
    @Menu(type = "callcenter" , subtype = "numberpool" , access = false )
    public ModelAndView add(ModelMap map , HttpServletRequest request , @Valid String hostid) {
		map.put("pbxHost", pbxHostRes.findByIdAndOrgi(hostid, super.getOrgi(request))) ;
    	return request(super.createRequestPageTempletResponse("/admin/callcenter/numberpool/add"));
    }
	
	@RequestMapping(value = "/save")
    @Menu(type = "callcenter" , subtype = "numberpool" , access = false )
    public ModelAndView extentionsave(ModelMap map , HttpServletRequest request , @Valid NumberPool numberPool) throws UnsupportedEncodingException {

		String msg = "";

		List<String> existNumber = new ArrayList<>();

		if(numberPool != null && StringUtils.isNotBlank(numberPool.getHostid())){

			String[] numbers = numberPool.getNumber().split("[,\\|，]");;

			if(numbers.length > 0 ){

				for(String nb : numbers){
					if(StringUtils.isNotBlank(nb)){
						NumberPool numberPoolTemp = new NumberPool();

						long count = numberPoolRepository.countByNumberAndHostid(nb,numberPool.getHostid());
						if(count > 0){
							existNumber.add(nb);
						}else{
							numberPoolTemp.setNumber(nb);
							numberPoolTemp.setCreatetime(new Date());
							numberPoolTemp.setCreater(super.getUser(request).getId());
							numberPoolTemp.setHostid(numberPool.getHostid());
							numberPoolTemp.setOrgi(super.getOrgi(request));
							numberPoolRepository.save(numberPoolTemp);
						}

					}
				}
			}

			if(existNumber != null && existNumber.size() > 0){
				msg = "以下号码已经存在：" + StringUtils.join(existNumber.toArray(), "，");
				msg = URLEncoder.encode(msg,"UTF-8");
			}

		}
		return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/numberpool/index.html?hostid="+numberPool.getHostid() + "&msg=" + msg));
    }
	
	@RequestMapping(value = "/edit")
    @Menu(type = "callcenter" , subtype = "callcenterrate" , access = false )
    public ModelAndView edit(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String hostid) {
		map.put("numberPool" , numberPoolRepository.findById(id));
    	return request(super.createRequestPageTempletResponse("/admin/callcenter/numberpool/edit"));
    }
	
	@RequestMapping(value = "/update")
    @Menu(type = "callcenter" , subtype = "numberpool" , access = false )
    public ModelAndView update(ModelMap map , HttpServletRequest request , @Valid NumberPool numberPool) throws UnsupportedEncodingException {
		String msg = "";
		if(!StringUtils.isBlank(numberPool.getId())){

			NumberPool oldNumberPool = numberPoolRepository.findById(numberPool.getId()) ;

			if(oldNumberPool!=null){
				numberPool.setHostid(oldNumberPool.getHostid());

				long count = numberPoolRepository.countByNumberAndHostidAndIdNot(numberPool.getNumber(),oldNumberPool.getHostid(),oldNumberPool.getId());

				if(count > 0 ){
					msg = "以下号码已经存在：" + numberPool.getNumber();
					msg = URLEncoder.encode(msg,"UTF-8");
				}else{
					oldNumberPool.setUpdatetime(new Date());
					oldNumberPool.setUpdater(super.getUser(request).getId());
					oldNumberPool.setNumber(numberPool.getNumber());
					oldNumberPool.setHostid(numberPool.getHostid());
					numberPoolRepository.save(oldNumberPool);
				}
			}
		}
		return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/numberpool/index.html?hostid="+numberPool.getHostid() + "&msg=" + msg));
    }
	
	@RequestMapping(value = "/delete")
	@Menu(type = "callcenter" , subtype = "numberpool" , access = false )
	public ModelAndView delete(ModelMap map , HttpServletRequest request,@Valid String[] ids,@Valid String hostid) {
		if(ids != null && ids.length > 0){
			for(String id : ids){
				if (StringUtils.isNotBlank(id)) {
					numberPoolRepository.delete(id);

					//同时删除绑定信息
					List<NumberPoolExtentionRela> numberPoolExtentionRelasList = numberPoolExtentionRelaRepository.findByExtentionid(id);
					if(numberPoolExtentionRelasList != null && numberPoolExtentionRelasList.size() > 0){
						numberPoolExtentionRelaRepository.delete(numberPoolExtentionRelasList);
					}
				}
			}
		}
		return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/numberpool/index.html?hostid="+hostid));
	}

}
